<template>
  <view class="hb-w-full hb-h-full hb-relative hb-flex hb-flex-col">
    <!-- 粘性定位头部，放在scroll-view外面 -->
    <view class="hb-bg-white hb-w-full hb-flex-shrink-0">
      <view class="hb-flex hb-items-center hb-justify-between hb-mb-4">
        <view class="hb-flex hb-items-center">
          <TmIcon name="ali-icon icon-remarks" color="primary" :font-size="40" />
          <TmText class="hb-ml-2" _class="hb-font-bold" label="文档信息" :font-size="28" />
        </view>
        <TmButton
          :margin="[0, 0]"
          icon="ali-icon icon-shangchuan1"
          :width="232"
          :round="12"
          :height="48"
          :font-size="24"
          label="从微信聊天上传"
          color="primary"
          @click="onUpload"
        />
      </view>

      <TmText
        _class="hb-mb-3"
        label="上传个人、公司、业务、产品等信息，让智能助手更加懂你"
        color="#646566"
        :font-size="24"
      />
      <TmText
        _class="hb-mb-3"
        label="当前文件仅支持10MB以内的word、PPT、PDF文件。"
        color="#646566"
        :font-size="24"
      />

    </view>

    <!-- 滚动内容区域 -->
    <scroll-view
      enable-passive
      enhanced
      :show-scrollbar="false"
      scroll-y
      class="hb-w-full hb-flex-1 hb-h-0"
      @scrolltolower="onScrollToLower"
    >
      <template v-for="item in fileList" :key="item.id">
        <FileResourceItem :item="item" :show-setting="true" @refresh="refreshFileList" />
      </template>
      <Loadmore v-if="fileList.length >= 10" :loading-type="loadingType" />
      <Empty v-if="fileList.length === 0" />
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
  import FileResourceItem from './FileResourceItem.vue';
  import { knowledgeBaseFileList, knowledgeBaseFileSave } from '@/api/knowledgeBase';
  import { KnowledgeBaseFileListResult } from '@/api/knowledgeBase/types';
  import { IQuery } from '@/api/types';

  defineOptions({
    name: 'FileResource',
  });

  const fileDefaultSize = 10;
  function verifyFileSize(fileSize: number): boolean {
    const is = fileDefaultSize * 1024 * 1024 > fileSize;
    return is;
  }

  const onUpload = () => {
    uni.chooseMessageFile({
      count: 5,
      type: 'file',
      extension: ['doc', 'docx', 'ppt', 'pptx', 'pdf', 'md'],
      success: (res) => {
        const list: UniApp.ChooseFile[] = [];
        const errFilesName: string[] = [];
        res.tempFiles.forEach((item) => {
          if (verifyFileSize(item.size)) {
            list.push(item);
          } else {
            errFilesName.push(`"${item.name}"`);
          }
        });

        handleUploadModal(list, errFilesName);
      },
    });
  };

  function handleUploadModal(fileList: UniApp.ChooseFile[], errFilesName: string[]) {
    if (errFilesName.length > 0) {
      let content = `${errFilesName.join(',')}文件大小超过${fileDefaultSize}MB`;
      if (fileList.length) {
        content += `，是否继续上传其他文件？`;
      } else {
        content += `，是否重新选择文件？`;
      }
      uni.showModal({
        title: '提示',
        content,
        cancelText: '取消',
        confirmText: fileList.length > 0 ? '继续上传' : '重新选择',
        cancelColor: '#969799',
        confirmColor: '#2878FF',
        success: (res) => {
          if (res.confirm) {
            fileList.length ? uploadFile(fileList) : onUpload();
          }
        },
      });
    } else {
      uploadFile(fileList);
    }
  }

  async function uploadFile(fileList: UniApp.ChooseFile[]) {
    uni.showLoading({
      title: '上传中...',
    });
    try {
      const requestList = fileList.map((item) => {
        return knowledgeBaseFileSave({
          name: item.name,
          path: item.path,
          size: item.size,
        });
      });
      await Promise.all(requestList);
      refreshFileList();
    } catch (error) {
    } finally {
      uni.hideLoading();
    }
  }

  const fileList = ref<KnowledgeBaseFileListResult[]>([]);

  const query = reactive<IQuery>({
    current: 1,
    size: 10,
  });

  const loadingType = ref(0);

  // 获取文件列表
  async function getFileList() {
    const res = await knowledgeBaseFileList(unref(query));
    loadingType.value = res.records.length === 0 ? 2 : 0;
    fileList.value = [...fileList.value, ...res.records];
  }

  /** 刷新数据 */
  function refreshFileList() {
    fileList.value = [];
    query.current = 1;
    getFileList();
  }

  refreshFileList();

  const onScrollToLower = async () => {
    console.log('onScrollToLower');
    if (loadingType.value === 1 || loadingType.value === 2) return;
    loadingType.value = 1;
    query.current++;
    await getFileList();
  };
</script>